﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCFMINERP.DAL;
using WCFMINERP.COM;
using WCFMINERP.InnerFactoryContracts.DataContracts;
using System.Data.Objects;



namespace WCFMINERP.BLL.PrintShopBill
{
    public  class PrintShopBillBLL
    {
        private WorkFlowListBLL _wflBll =new WorkFlowListBLL();
         /// <summary>
         /// 扫描接收
         /// </summary>
         /// <param name="barCode"></param>
         /// <param name="OperateUid"></param>
         /// <param name="techId"></param>
         /// <param name="errorMsg"></param>
        /// <returns>0接收成功，1产品全部流程已完成，2产品有错误，3产品生产停止，4产品生产完成，5未知异常，6此产品还未到达本岗位,没有找到状态为1的结点
        /// 7没有找到此产品的相关委外记录,请确认这个产品的流程是否正确!,8该产品未到本岗位，请到客服产看该产品信息!,9在委外记录表中未找到此产品的相关的委外的记录!
        /// 
        /// </returns>
        public int ReceiveBarCode(string barCode, int OperateUid, int techId, out string  errorMsg,out OrderInfo_Info orderInfo)
        {
            int ret = 0;
            errorMsg = "";
            orderInfo = null;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                orderInfo oi = db.orderInfo.FirstOrDefault(p => p.OrderProductCode == barCode);
                if (oi != null)
                {

                    if (!oi.Tb_OrderBagReference.IsLoaded)
                    {
                        oi.Tb_OrderBagReference.Load();
                    }
                    if (!oi.Tb_OrderBag.ShopReference.IsLoaded)
                    {
                        oi.Tb_OrderBag.ShopReference.Load();
                    }
                    orderInfo = new OrderInfo_Info()
                    {
                        OrderProductId = oi.OrderProductId,
                        ShopName = oi.Tb_OrderBag.Shop.shopName,
                        CtmName = oi.CtmName,
                        OrderProductName = oi.OrderProductName,
                        Status = oi.status,
                        Remark = oi.Remark,
                        OrderProductCode = oi.OrderProductCode
                    };
                }
                else
                {
                    errorMsg = "产品号不存在或产品全部流程已完成！";
                    ret = 1;
                    return ret;

                }
                users OperateUser = db.users.FirstOrDefault(p => p.userID == OperateUid);
              
                if (oi.status != (int)OrderInfoStatus.Doing)
                {

                    //return null;//提示扫描的条码不正确
                    switch ((OrderInfoStatus)oi.status)
                    {

                        case OrderInfoStatus.Error: 
                            errorMsg ="该产品有错误,具体情况请查询客服！";
                            ret = 2;
                            return ret;
                        case OrderInfoStatus.Stop: 
                             errorMsg ="该产品是已停止,具体情况请查询客服！";
                             ret = 3;
                             return ret;
                        case OrderInfoStatus.Completed: 
                             errorMsg ="产品是已完成,具体情况请查询客服！";
                             ret = 4;
                             return ret;
                        default: 
                             errorMsg ="该产品无法处理,具体情况请查询客服！";
                             ret = 5;
                             return ret;
                    }

                }
                else
                {
                    if (!oi.WorkOrderFlowList.IsLoaded)
                    {
                        oi.WorkOrderFlowList.Load();
                    }
                   
                    WorkOrderFlowList wfl = oi.WorkOrderFlowList.FirstOrDefault(w => w.Status == (int)OrderFlowListStatus.Useable);
                    if (wfl == null)
                    {
                        errorMsg = "此产品还未到达本岗位,没有找到状态为1的结点！（可能是没有刷新，新重启程序）";
                        ret = 6;
                        return ret;

                    }
                    else
                    {
                        if (!wfl.tb_TechReference.IsLoaded)
                        {
                            wfl.tb_TechReference.Load();
                        }
                        if (wfl.tb_Tech.TechId == techId)//当前流程在分堆
                        {
                            //调用商户分堆模块
                            
                            AssignShopGrid(oi, OperateUser);
                        }
                        else//当前流程不在理件分堆
                        {
                            if (!oi.OutProcessRecord.IsLoaded)
                            {
                                oi.OutProcessRecord.Load();
                            }
                    
                            if (oi.OutProcessRecord.Count < 1)
                            {
                                errorMsg = "没有找到此产品的相关委外记录,请确认这个产品的流程是否正确!";
                                ret = 7;
                                return ret;
                 
                            }
                            else
                            {
                                if (wfl.tb_Tech.TechType != (int)TechType.OutProduct)
                                {
                                     errorMsg ="该产品未到本岗位，请到客服产看该产品信息!";
                                     ret = 8;
                                     return ret;

                                }
                                if (oi.OutProcessRecord == null)
                                {
                                    errorMsg ="在委外记录表中未找到此产品的相关的委外的记录!";
                                    ret = 9;
                                    return ret;

                                }

                                OutProcessRecord opr = oi.OutProcessRecord.FirstOrDefault(op => op.Status == (int)OutProcessRecordStatus.Outing || op.Status == (int)OutProcessRecordStatus.OutWaitFenDui || op.Status == (int)OutProcessRecordStatus.InGrid);
                                if (opr == null)
                                {
                                    OutProcessRecord errOutRecord = oi.OutProcessRecord.FirstOrDefault(p => p.Status == (int)OutProcessRecordStatus.Fetched);
                                    if (errOutRecord != null)
                                    {
                                        errOutRecord.Status = (int)OutProcessRecordStatus.Outing;
                                        db.SaveChanges();
                                        errorMsg ="请再试一次!";
                                        ret = 10;
                                        return ret;

                                    }
                                }
                                else
                                {
                                    //工厂端完成要完了才调用分堆模块
                                    if (opr.Status == (int)OutProcessRecordStatus.Outing)
                                    {
                                        //if (opr.Status2 == (int)OutProcessRecordStatus2.Complete)
                                        //{
                                            //调用收件确认流程
                                            if (!FetchAndSure(oi, OperateUser, wfl.tb_Tech.TechId, opr,db))
                                            {
                                                errorMsg ="收件确认出错，请重试!";
                                                ret = 11;
                                                return ret;
                                            }
                                            else
                                            {
                                                if (CheckOrderInfoTech(oi, techId,db))
                                                {
                                                    AssignShopGrid(oi, OperateUser);
                                                }
                                                else
                                                {
                                                    //提示用户此产品现在应处于哪个结点
                                                    tb_Tech tt = GetOrderInfoEnabelTechInfo(oi,db);
                                                    if (tt == null)
                                                    {
                                                        errorMsg = "产品流程错误,请检查该产品是否此完成!";
                                                        ret = 12;
                                                        return ret;
                                                    }      
                                                    errorMsg = "此产品还未到本岗位，请将此产品送到:" + tt.TechName + "岗位";
                                                    ret = 13;
                                                    return ret;
                                                }
                                            }
                                        //}
                                        //else
                                        //{
                                        //    errorMsg ="此产品已打印委外单，正在外加工中！";
                                        //    ret = 14;
                                        //    return ret;
                                        //}
                                    }
                                    else 
                                    {
                                        errorMsg = "还未打印委外单！";
                                        ret = 15;
                                        return ret;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return ret;
        }

        private bool CheckOrderInfoTech(orderInfo orderInfo, int techId,newSampleYPDBEntities db)
        {
            bool flag =false;

            orderInfo oi =db.orderInfo.First(o=>o.OrderProductId ==orderInfo.OrderProductId); 
            if (!oi.WorkOrderFlowList.IsLoaded)
            {
                oi.WorkOrderFlowList.Load();
            }
            WorkOrderFlowList wfl = oi.WorkOrderFlowList.FirstOrDefault(w => w.Status == (int)OrderFlowListStatus.Useable);
            if (wfl == null)
            {
                return false;
            }
            else
            {
                if (!wfl.tb_TechReference.IsLoaded)
                {
                    wfl.tb_TechReference.Load();
                }
                if(wfl.tb_Tech.TechId ==techId)
                {
                    flag =true;
                }
                else
                {
                    flag =false;
                }
            }
            return flag;
        }

        private tb_Tech GetOrderInfoEnabelTechInfo(orderInfo orderInfo,newSampleYPDBEntities db)
        {
            tb_Tech tech = null;
            orderInfo oi = db.orderInfo.First(o => o.OrderProductId == orderInfo.OrderProductId);
            if (!oi.WorkOrderFlowList.IsLoaded)
            {
                oi.WorkOrderFlowList.Load();
            }
            WorkOrderFlowList wfl = oi.WorkOrderFlowList.FirstOrDefault(w => w.Status == (int)OrderFlowListStatus.Useable);
            if (wfl == null)
            {
                return null;
            }
            else
            {
                if (!wfl.tb_TechReference.IsLoaded)
                {
                    wfl.tb_TechReference.Load();
                }
                tech = wfl.tb_Tech;
            }

            return tech;
 
        }

        /// <summary>
        /// 商户分堆模块
        /// </summary>
        /// <param name="oi"></param>
        /// <param name="operateUser"></param>
        /// <returns></returns>
        private void AssignShopGrid(orderInfo orderInfo, users operateUser)
        {
            using (newSampleYPDBEntities db =new  newSampleYPDBEntities())
            {
                orderInfo oi = db.orderInfo.First(o=>o.OrderProductId==orderInfo.OrderProductId);
                
                if (!oi.Tb_OrderBagReference.IsLoaded)
                {
                    oi.Tb_OrderBagReference.Load();
                }
                if (!oi.Tb_OrderBag.ShopReference.IsLoaded)
                {
                    oi.Tb_OrderBag.ShopReference.Load();
                }
                Shop shop = oi.Tb_OrderBag.Shop;

                try
                {
                    //委外账单 修改状态

                    int intOutProduct = (int)OutProcessProductStatus.Received;

                    OutShopBillDetail detail = db.OutShopBillDetail.FirstOrDefault(p => p.OrderProductCode == oi.OrderProductCode);
                    if (detail != null)
                    {


                        detail.ProductStatus = intOutProduct; //委外产品已经收到
                        detail.OutShop_BillReference.Load();
                        OutShop_Bill bill = detail.OutShop_Bill;
                        bill.OutShopBillDetail.Load();
                        List<OutShopBillDetail> list = bill.OutShopBillDetail.ToList();

                        int rectiveCount = list.Count(p => p.ProductStatus == intOutProduct);
                        decimal summedReceive = list.Where(p => p.ProductStatus == intOutProduct).Sum(p => p.UnitPrice * p.Num);
                        if (rectiveCount == list.Count())
                        {
                            bill.ProductSratus = (int)OutProcessProductStatus.Complete;
                        }
                        else
                        {
                            bill.ProductSratus = (int)OutProcessProductStatus.Received;
                        }


                        bill.SummedRecive = summedReceive;

                    }
                    else
                    {
                        //记录在日志中
                    }

                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }


        /// <summary>
        /// 收件确认模块
        /// </summary>
        /// <param name="oi"></param>
        /// <param name="operateUser"></param>
        /// <returns></returns>
        private bool FetchAndSure(orderInfo oi, users operateUser, int techId, OutProcessRecord opr,newSampleYPDBEntities db)
        {
            if (_wflBll.OverCurTech(techId, operateUser.userID, oi, db))
            {
                opr.Status = (int)OutProcessRecordStatus.Fetched;
                opr.users1 = operateUser;
                //opr.FetchTime = DateTime.Now;
                opr.FetchRemark = "黙认收件"; //
                db.SaveChanges();
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 通过节点类型获得节点Id
        /// </summary>
        /// <param name="techType"></param>
        /// <returns></returns>
        public int GettechId(int techType)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                tb_Tech tech = db.tb_Tech.FirstOrDefault(t=>t.TechType==techType);
                if (tech != null)
                {
                    return tech.TechId;
                }
                else
                {
                    return 0;
                }
            }
        }



        /// <summary>
        /// 去掉msdtc事务后的分堆逻辑处理
        /// </summary>
        /// <param name="curTechId"></param>
        /// <param name="operUid"></param>
        /// <param name="grid_Info"></param>
        /// <param name="SelectOrderInfo"></param>
        /// <param name="hasAllProd"></param>
        /// <param name="hasForcibePrint"></param>
        /// <param name="inPay"></param>
        /// <returns></returns>
        public SHOP_Bill_Info NewOrderComplete(int curTechId, int operUid, List<OrderInfo_Info> SelectOrderInfo, bool hasForcibePrint, int inPay)
        {

            int Bill_Detail_Id = 1;                             //用于报表中的关联ID，与数据库实际的ID并不一样


            List<int> ListOrderProductId = SelectOrderInfo.Select(p => p.OrderProductId).ToList();
            List<int> DonedOrderProudctId = new List<int>(ListOrderProductId);//能够正常结帐单的产品ID


            double Bill_Price = 0;                              //此帐单的总价格
            Shop curShop;                                       //当前商户


            SHOP_Bill_Info sbinfo = new SHOP_Bill_Info();       //用于返回给打印页面使用
            SHOP_Bill sb = new SHOP_Bill();                     //用于向数库添加数据

            List<Tb_OrderBag> NeedMoveDataOrderList = new List<Tb_OrderBag>();//需要转移数据的定单包列表
            bool isNeedMoveData = false;
            bool isNeedOverOrderInfo = false;//是否需要完产品流程

            //初始信息
            sb.NeedDeliver = 1;                                 //是否需要配送   
            sb.Status = (int)ShopBillStatus.UnCheckOut;

            sb.CreateTime = CommonMethodDAL.GetServerTime();//获取系统时间
            sbinfo.CreateTime = sb.CreateTime;//获取系统时间


            sbinfo.List_Detail = new List<Bill_Detail_Info>();


            //TransactionOptions options = new TransactionOptions();
            //options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            //using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, options))
            //{
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                if (db.Connection.State != System.Data.ConnectionState.Open)
                {
                    db.Connection.Open();
                }

                using (System.Data.Common.DbTransaction tran = db.Connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                {
                    try
                    {
                        string shopName = SelectOrderInfo.First().ShopName;
                        int shopId = db.Shop.FirstOrDefault(p => p.shopName == shopName).ShopId;

                        curShop = db.Shop.FirstOrDefault(p => p.ShopId == shopId);
                        SalesmanBalance salesmanBalance = null;
                        salesmanBalance = db.SalesmanBalance.FirstOrDefault(s => s.SalesmanName == curShop.Salesman);

                        string CheckType = "";
                        switch (curShop.CheckOutType)
                        {
                            case 0:
                                CheckType = "预付款";
                                break;
                            case 1:
                                CheckType = "信用额度";

                                break;
                            case 2:
                                CheckType = "现结";
                                break;
                            case 3:
                                CheckType = "结账日期";

                                break;
                            case 4:
                                CheckType = "结账日期与信用额度";

                                break;
                            case 5:
                                CheckType = "先结";
                                break;
                            case 6:
                                CheckType = "代收";
                                break;
                            default:
                                break;
                        }
                        sbinfo.CheckType = CheckType;
                        #region 得到商户的帐单的顺序号

                        List<SHOP_Bill> listShopBill = db.SHOP_Bill.Where(s => s.CreateTime.Month == sb.CreateTime.Month && s.CreateTime.Year == sb.CreateTime.Year && s.Shop.ShopId == shopId).ToList();
                        if (listShopBill.Count <= 0)
                        {
                            sb.BillOrderCode = 1;
                        }
                        else
                        {
                            sb.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                        }


                        //sb.BillOrderCode = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == DateTime.Now.Month && s.Shop.ShopId == shopId).Max(a => a.BillOrderCode) + 1;

                        sbinfo.BillOrderCode = sb.BillOrderCode;



                        #endregion

                        foreach (var orderProductId in ListOrderProductId.Distinct())
                        {
                            if (true)
                            {
                                isNeedOverOrderInfo = true;
                                #region 帐单名细--每一层，就是产品（orderinfo）

                                decimal orderInfoPrice = 0;//此产品的真实价格

                                orderInfo oi = db.orderInfo.Include("photoInfo").FirstOrDefault(p => p.OrderProductId == orderProductId);

                                if (oi.status == (int)OrderInfoStatus.Completed)
                                {
                                    db.Refresh(System.Data.Objects.RefreshMode.StoreWins, oi);
                                }

                                #region 加载数据库
                                if (!oi.Tb_ProductReference.IsLoaded)
                                {
                                    oi.Tb_ProductReference.Load();
                                }
                                if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
                                {
                                    oi.Tb_Product.tb_CostTypeReference.Load();
                                }
                                if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                                {
                                    oi.Tb_Product.Tb_PorductCategoryReference.Load();
                                }
                                if (!curShop.Shop_Product_Price.IsLoaded)
                                {
                                    curShop.Shop_Product_Price.Load();
                                }
                                if (!oi.photoInfo.IsLoaded)
                                {
                                    oi.photoInfo.Load();
                                }
                                if (!oi.Tb_OrderBagReference.IsLoaded)
                                {
                                    oi.Tb_OrderBagReference.Load();
                                }
                                string orderBagName = oi.Tb_OrderBag.BagName.Split('_')[0];

                                #endregion

                                Bill_Detail bd = new Bill_Detail() { OiRemark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, IsCheckOut = false };
                                Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = oi.Remark, OrderInfoCode = oi.OrderProductId.ToString(), OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, OrderBagName = orderBagName };
                                Bill_Detail_Id++;
                                dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();



                                orderInfoPrice = BillBLL.GetOrderPrice(curShop, oi, db, bd);

                                ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);


                                #region 如果产品满足财务信息，则可以找印帐单，并判断登陆者的权限在“在余额不足”情况下是否可以打帐单

                                #region //对帐户金额的操作
                                ShopBlanceCrushRecord br;
                                switch (curShop.CheckOutType)
                                {
                                    case 0://预付款用户
                                    case 2://现结用户
                                    case 5://先结
                                        #region
                                        curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;

                                        if (curShop.OrderBalance < 0)
                                        {
                                            curShop.OrderBalance = 0;
                                        }


                                        if (curShop.Balance < (decimal)orderInfoPrice)
                                        {
                                            //curShop = db.Shop.FirstOrDefault(pt => pt.ShopId == shopId);
                                            //如果余额不足，就判断是否有权限可打印此帐单
                                            if (hasForcibePrint)//可以强打
                                            {
                                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                                                // dataBase.Refresh(RefreshMode.StoreWins, curShop);
                                                curShop.Balance -= (decimal)orderInfoPrice;
                                                //向商户帐户记录表添加记录
                                                br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                                db.AddToShopBlanceCrushRecord(br);

                                            }
                                            else
                                            {
                                                oi.status = (int)OrderInfoStatus.WaitPay;
                                                //dataBase.Refresh(RefreshMode.StoreWins, curShop);
                                                curShop.OrderBalance += oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                                isNeedOverOrderInfo = false;
                                                DonedOrderProudctId.Remove(oi.OrderProductId);
                                            }
                                        }
                                        else
                                        {

                                            bd.IsCheckOut = true;
                                            //dataBase.Refresh(RefreshMode.StoreWins, curShop);
                                            curShop.Balance -= (decimal)orderInfoPrice;

                                            //向商户帐户记录表添加记录
                                            br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                            db.AddToShopBlanceCrushRecord(br);
                                        }
                                        if (salesmanBalance != null)//对业务员账户操作
                                        {
                                            //dataBase.Refresh(RefreshMode.StoreWins, salesmanBalance);
                                            salesmanBalance.Balance -= (decimal)orderInfoPrice;
                                        }
                                        //检查是否需要报警
                                        if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                        {
                                            BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);
                                        }
                                        #endregion
                                        break;
                                    case 1://信用额度用户
                                    case 3://结帐日用户
                                    case 4://结单日与信用额度用户
                                    case 6://代收款
                                        #region

                                        curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                        if (curShop.OrderBalance < 0)
                                        {
                                            curShop.OrderBalance = 0;
                                        }
                                        //dataBase.Refresh(RefreshMode.StoreWins, curShop);
                                        curShop.Balance -= (decimal)orderInfoPrice;
                                        if (salesmanBalance != null)//对业务员账户操作
                                        {
                                            // dataBase.Refresh(RefreshMode.StoreWins, salesmanBalance);
                                            salesmanBalance.Balance -= (decimal)orderInfoPrice;
                                        }
                                        if (curShop.CheckOutType == 1)//信用额度用户
                                        {
                                            if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                            {
                                                BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);

                                            }
                                        }
                                        else
                                        {
                                            int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                            if (days > 0 && days < curShop.AlarmDays)
                                            {
                                                BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);
                                            }
                                        }

                                        //向商户帐户记录表添加记录
                                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                        db.AddToShopBlanceCrushRecord(br);
                                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                                        #endregion
                                        break;
                                    default:
                                        break;
                                }

                                #endregion

                                if (isNeedOverOrderInfo)
                                {

                                    bool result = _wflBll.OverCurTech(curTechId, operUid, oi, db, out isNeedMoveData);

                                    if (!result)
                                    {
                                        
                                        throw new Exception(oi.OrderProductCode + "请检查此产品是否被暂停，如未被暂停，请重启程序！" + "(节点:" + curTechId.ToString() + "操作员:" + operUid.ToString());
                                    }
                                    else
                                    {
                                        if (isNeedMoveData)
                                        {
                                            NeedMoveDataOrderList.Add(oi.Tb_OrderBag);
                                        }

                                        #region//在此修改相应的业绩记录
                                        double orderArea = -1;
                                        List<New_EmployeePerformance> emList = db.New_EmployeePerformance.Where(e => e.OrderproductId == oi.OrderProductId).ToList();
                                        foreach (var em in emList)
                                        {
                                            if (orderArea == -1)
                                            {
                                                if (!oi.Tb_ProductReference.IsLoaded)
                                                    oi.Tb_ProductReference.Load();
                                                if (!oi.Tb_Product.tb_ProductTypeReference.IsLoaded)
                                                {
                                                    oi.Tb_Product.tb_ProductTypeReference.Load();
                                                }

                                                Shop_Product_Price spp = db.Shop_Product_Price.FirstOrDefault(sp => sp.Shop.ShopId == curShop.ShopId && sp.Tb_Product.ProuctId == oi.Tb_Product.ProuctId);
                                                spp.tb_CostTypeReference.Load();
                                                if (spp.tb_CostType.CostTypeId == 1 || spp.tb_CostType.CostTypeId == 4)
                                                {
                                                    //orderArea=
                                                    if (oi.Tb_Product.tb_ProductType.ProductTypeCode == 5 || oi.Tb_Product.tb_ProductType.ProductTypeCode == 6)
                                                    {
                                                        orderArea = oi.productNum * (oi.photoInfo.Sum(ph => (double)ph.TotalNum) * oi.Tb_Product.Width * oi.Tb_Product.Height * 2.54 * 2.54 / 10000);
                                                    }
                                                    else
                                                    {
                                                        orderArea = oi.photoInfo.Sum(ph => ph.Height * ph.Width * 2.54 * 2.54 / 10000);
                                                    }
                                                }
                                                else
                                                {
                                                    orderArea = dbinfo.ListDetail_Detail.Where(bddt => bddt.Type == (int)Bill_Detail_Detail_Type.NeedStatArea).Sum(bddt => bddt.Area);
                                                }
                                            }
                                            if (em != null)
                                            {
                                                em.OrderCount = orderInfoPrice;
                                                em.Status = (int)OrderInfoStatus.Completed;
                                                em.OrderConpletedTime = oi.CompleteTime;
                                                em.OrderArea = orderArea;
                                                em.ProductPhotoNum = Convert.ToInt32(oi.productNum * (oi.photoInfo.Sum(ph => ph.TotalNum)));
                                            }
                                        }
                                        #endregion

                                        sb.Bill_Detail.Add(bd);

                                        dbinfo.BillDetailId = Bill_Detail_Id;
                                        sbinfo.List_Detail.Add(dbinfo);
                                        Bill_Detail_Id++;
                                        Bill_Price += (double)orderInfoPrice;
                                    }
                                }

                                #endregion

                                #endregion
                            }
                        }
                        //添加运费项目
                        if (inPay > 0)
                        {
                            #region 收费项目
                            Bill_Detail bd = new Bill_Detail() { OiRemark = "运费", OrderInfoCode = "0", OrderProductName = "运费", CtmName = curShop.shopName, IsCheckOut = false };
                            Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = "运费", OrderInfoCode = "0", OrderProductName = "运费", CtmName = curShop.shopName };
                            dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();
                            Bill_Detail_Id++;

                            bd.Bill_Detail_Detail.Add(new Bill_Detail_Detail()
                            {
                                Area = 0,
                                Count = inPay,
                                DetailName = "运费",
                                Num = 1,
                                Spec = "",
                                Type = 0,
                                UnitPrice = inPay
                            });

                            ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);

                            sb.Bill_Detail.Add(bd);

                            dbinfo.BillDetailId = Bill_Detail_Id;
                            sbinfo.List_Detail.Add(dbinfo);
                            Bill_Detail_Id++;
                            Bill_Price += (double)inPay;

                            ShopBlanceCrushRecord br;
                            switch (curShop.CheckOutType)
                            {
                                case 0://预付款用户
                                case 2://现结用户
                                    #region
                                    //curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                    if (curShop.OrderBalance < 0)
                                    {
                                        curShop.OrderBalance = 0;
                                    }


                                    if (curShop.Balance < (decimal)inPay)//默认都是强大
                                    {
                                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                                        curShop.Balance -= (decimal)inPay;
                                        //向商户帐户记录表添加记录
                                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                        db.AddToShopBlanceCrushRecord(br);
                                    }
                                    else
                                    {

                                        bd.IsCheckOut = true;
                                        curShop.Balance -= (decimal)inPay;

                                        //向商户帐户记录表添加记录
                                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                        db.AddToShopBlanceCrushRecord(br);
                                    }

                                    //检查是否需要报警
                                    if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "运费：" + inPay + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);
                                    }
                                    #endregion
                                    break;
                                case 1://信用额度用户
                                case 3://结帐日用户
                                case 4://结单日与信用额度用户 
                                    #region
                                    //curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                    if (curShop.OrderBalance < 0)
                                    {
                                        curShop.OrderBalance = 0;
                                    }
                                    curShop.Balance -= (decimal)inPay;

                                    if (curShop.CheckOutType == 1)//信用额度用户
                                    {
                                        if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                        {
                                            BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "运费：" + inPay + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);

                                        }
                                    }
                                    else
                                    {
                                        int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                        if (days > 0 && days < curShop.AlarmDays)
                                        {
                                            BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "运费:" + inPay + "当前余额为：" + curShop.Balance, curShop, db, sb.CreateTime);
                                        }
                                    }

                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)inPay, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "运费：系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    db.AddToShopBlanceCrushRecord(br);
                                    sb.Status = (int)ShopBillStatus.UnCheckOut;
                                    #endregion
                                    break;
                                default:
                                    break;
                            }
                            #endregion 收费项目
                        }


                        //记录帐单信息            

                        sb.Shop = curShop;
                        sb.TotalPrice = (decimal)Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                        sbinfo.Shop = new ShopInfo() {  address = curShop.address, ShopId = curShop.ShopId,  shopKeeper = curShop.shopKeeper, shopName = curShop.shopName, Tel1 = curShop.Tel1, Tel2 = curShop.Tel2,  IsNeedPrintUPrice  = curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice, Salesman = curShop.Salesman, CreditLevel = curShop.CreditLevel == null ? 0 : (int)curShop.CreditLevel, QQ =curShop.QQ, Remark =curShop.Remark};
                        sbinfo.ShopBalance = (double)curShop.Balance;//指商户的总共欠款额度(包括本帐单)

                        //sbinfo.BillCount = Bill_Price;
                        sbinfo.BillCount = Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                        if (sb.Bill_Detail.Count(a => a.OrderInfoCode != "0") > 0)
                        {
                            if (sb.Bill_Detail.Count(b => !b.IsCheckOut) > 0)
                            {
                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                            }
                            else
                            {
                                sb.Status = (int)ShopBillStatus.CheckedOut;
                            }
                            sb.ShopBalance = curShop.Balance ?? 0;
                            db.AddToSHOP_Bill(sb);

                            db.SaveChanges();
                            //db.AcceptAllChanges();
                            tran.Commit();
                        }
                        else
                        {
                            sbinfo = null;
                            sb = null;
                            tran.Rollback();
                        }
                        if (sbinfo != null)
                        {
                            sbinfo.BillId = sb.BillId;
                            sbinfo.List_Detail = sbinfo.List_Detail.OrderBy(ld => ld.CtmName).ToList();//按客户名称排个序                       
                        }
                        return sbinfo;
                    }
                    catch (Exception ex)
                    {
                        WriteAnalyseLog.WriteLogFile(DateTime.Now + ex.Message);
                        tran.Rollback();
                        throw ex;
                    }
                }
            }
        }

        /// <summary>
        /// 将Bill_Detail转换为要打印的信息
        /// </summary>
        /// <param name="bd"></param>
        /// <param name="curShop"></param>
        /// <param name="bdInfo"></param>
        private void ConvertOrderDetailaToViewModel(Bill_Detail bd, Shop curShop, Bill_Detail_Info bdInfo)
        {
            foreach (var bdd in bd.Bill_Detail_Detail.ToList())
            {
                bdInfo.ListDetail_Detail.Add(new Bill_Detail_Detail_Info()
                {
                    Area = bdd.Area,
                    Count = bdd.Count,
                    DetailName = bdd.DetailName,
                    Num = bdd.Num,
                    Spec = bdd.Spec,
                    Type = bdd.Type ?? 0,
                    UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0,
                    Bill_Detail_DetailId = bdInfo.BillDetailId,
                    DetailRemark = bdd.DetailRemark
                });
            }
        }
    }
}
